'''
Created on Aug 8, 2011

@author: zhou,gang
'''

import smtplib, traceback
from common import framework
from email.MIMEText import MIMEText
from common.config import MAIL_SERVER_ADDR, MAIL_FROM, MAIL_TO_LIST, MAIL_SUBJECT, MAIL_SEND, MAIL_SUPPORT_TO, MAIL_SUPPORT_SUBJECT

content_prefix = 'This message is sent by server automatically!\n\n'
user_info = 'User id is: %s\n\n' 

def send_mail(content = None,
              title = MAIL_SUBJECT,
              mail_to = MAIL_TO_LIST,
              mail_from = MAIL_FROM, is_sys_mail = True, append_trace_info = False):
    if not is_sys_mail or MAIL_SEND:
        try:
            content = __get_sys_content(content, append_trace_info)
            msg = MIMEText(content)
            msg['Subject'] = title
            msg['From'] = mail_from
            
            address_str = ';'.join(mail_to)
            msg['To'] = address_str
            
            
            s = smtplib.SMTP(MAIL_SERVER_ADDR)
    #        s.login('corp\is_portal','broadcaster')
            s.sendmail(mail_from, mail_to, msg.as_string())
            s.quit()
        except Exception,e:
            pass

def __get_sys_content(content, append_trace_info):
    if not append_trace_info:
        return content
    if content is None:
        content = traceback.format_exc()
    if type(content) in (tuple, list):
        content = '\n'.join(content)

    head_param = framework.get_server_key() 
    user_id = head_param[:head_param.index('|')]
    content = content_prefix + user_info % user_id + content
    return content

def send_sys_mail(content = None):
    if MAIL_SEND:
        send_mail(content, is_sys_mail = True, append_trace_info = True)
        
def send_feedback_mail(content):
    send_mail(content, MAIL_SUPPORT_SUBJECT, MAIL_SUPPORT_TO, is_sys_mail = False, append_trace_info = True)

def send_invite_mail(mail_to, mail_from):
    #contents = "test invitation contents"
    #subject = "test invitation title"
    #send_mail(contents, subject, mail_to, mail_from, is_sys_mail = False)
    return True

def send_html_email(html_content, subject, mail_to, mail_from):
    encoded_html_content = html_content.encode("utf_8", "replace")
    msg = MIMEText(encoded_html_content, "html", 'utf_8')
    msg["Subject"] = subject
    msg["From"] = mail_from
    msg["To"] = mail_to
    
    try:
        smtp_client = smtplib.SMTP(MAIL_SERVER_ADDR)
        return smtp_client.sendmail(mail_from, mail_to, msg.as_string())
    except Exception,e:
        print e
    finally:
        if smtp_client:
            smtp_client.quit()

if __name__ == "__main__" :
    """ Test Email Funcation"""
    print send_html_email("eeeeeeeeeeeeee", "test", "relin@microtrategy.com", "relin@microstrategy.com")

